
package ch.hearc.coursJava.exa3;

import junit.framework.Assert;

public class Addition
	{
	/*------------------------------------------------------------------*\
	|*							Methodes Public							*|
	\*------------------------------------------------------------------*/
	static int[] additionner(int[] tab1, int[] tab2)
		{
		Assert.assertTrue(tab1.length == tab2.length);
		int[] tabRes = new int[tab1.length];

		int nbCore = Runtime.getRuntime().availableProcessors();

		ThreadAdd[] threadAdds = new ThreadAdd[nbCore];
		Thread[] threads = new Thread[nbCore];

		startThreads(tab1, tab2, tabRes, nbCore, threadAdds, threads);
		joinThreads(threads);

		return tabRes;
		}

	/*------------------------------------------------------------------*\
	|*							Methodes Private						*|
	\*------------------------------------------------------------------*/
	private static void joinThreads(Thread[] threads)
		{
		try
			{
			for(Thread thread:threads)
				{
				thread.join();
				}
			}
		catch (Exception e)
			{
			System.err.println(e.toString());
			}
		}

	private static void startThreads(int[] tab1, int[] tab2, int[] tabRes, int nbCore, ThreadAdd[] threadAdds, Thread[] threads)
		{
		for(int i=0 ; i<nbCore ; i++)
			{
			threadAdds[i] = new ThreadAdd(tab1, tab2, tabRes, i, nbCore);
			threads[i] = new Thread(threadAdds[i]);
			threads[i].start();
			}
		}
	}

